package com.rh.number.builder;

import com.rh.number.entity.numberEntity;
import jakarta.persistence.Column;

import java.lang.reflect.Field;
import java.util.Map;

public class NumberSqlBuilder {
    public String buildFilterSql(Map<String, Object> params) {
        // 获取前端传入的驼峰格式字段名
        String field = (String) params.get("field");

        // 关键修改：通过实体类获取数据库列名
        String column = getColumnName(field);

        return "SELECT " + column + " AS filter_value, COUNT(*) AS count " +
                "FROM number GROUP BY " + column + " ORDER BY count DESC";
    }

    // 通过反射获取数据库列名
    private String getColumnName(String field) {
        try {
            Field classField = numberEntity.class.getDeclaredField(field);
            Column columnAnnotation = classField.getAnnotation(Column.class);
            return (columnAnnotation != null && !columnAnnotation.name().isEmpty())
                    ? columnAnnotation.name()
                    : field;
        } catch (NoSuchFieldException e) {
            throw new IllegalArgumentException("无效字段: " + field);
        }
    }
}